<template>
    <view class="container">
        <!-- Tab栏 -->
        <view class="bottom-tab">
            <view :class="classNameArr[0]" @click="changeTab(0)">公历</view>
            <view :class="classNameArr[1]" @click="changeTab(1)">农历</view>
        </view>

        <!-- 纪念日列表 -->
        <view class="task-list">
            <!-- 使用 uni-swipe-action 包裹每个 task-item -->
            <uni-swipe-action v-for="day in days" :key="day.id">
                <uni-swipe-action-item>
                    <!-- 左滑时显示的操作按钮 -->
                    <template v-slot:right>
                        <view class="swipe-buttons">
                            <button @click="handleEdit(day)" class="edit-btn">编辑</button>
                            <button @click="handleDelete(day.id)" class="delete-btn">删除</button>
                        </view>
                    </template>
                    <!-- 正常的 task-item 内容 -->
                    <view class="task-item">
                        <view class="task-time">
                            {{ day.targetTime }}
                        </view>
                        <text class="task-title">{{ day.title }}</text>
                        <view class="task-count-first">
                            <text>已过: {{ day.firstDays }} 天</text>
                        </view>
                        <view class="task-count-next">
                            <text>下次还剩: {{ day.nextDays }} 天</text>
                        </view>
                    </view>
                </uni-swipe-action-item>
            </uni-swipe-action>
        </view>

        <!-- 浮动按钮 -->
        <view class="floating-button" :style="{ left: `${position.left}px`, top: `${position.top}px` }"
            @touchstart="onTouchStart" @touchmove="onTouchMove" @touchend="onTouchEnd" @click="openDayPopup">
            <view class="plus-icon">+</view>
        </view>

        <!-- 添加纪念日的弹窗 -->
        <uni-popup ref="dayPopup" :show="showPopup" @close="showPopup = false">
            <view class="popup-content">
                <view class="form">
                    <input v-model="newDay.title" placeholder="纪念日标题" class="task-input" />
                    <view class="date-picker">
                        <picker mode="selector" :range="dateTypeOptions" @change="onDateTypeChange">
                            <view class="picker">
                                日期类型: {{ dateTypeOptions[newDay.type] }}
                            </view>
                        </picker>
                        <view class="form-item" @click="openSelectDate">
                            <view class="form-title">日期</view>
                            <input class="form-value" placeholder="请点击选择日期" v-model="newDay.targetTime"
                                :disabled="true" />
                        </view>
                        <datePicker @submit="handleSelectDate" title="纪念日日期" ref="pickerRef" maskColor="rgba(0,0,0,0.3)"
                            :defaultDate="defaultDate" :defaultLunar="defaultLunar"></datePicker>
                    </view>
                    <view class="button-group">
                        <button @click="addDay" class="add-button">完成</button>
                        <button @click="closeTaskPopup" class="cancel-button">取消</button>
                    </view>
                </view>
            </view>
        </uni-popup>
    </view>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue';
import UniPopup from '../../../uni_modules/uni-popup/components/uni-popup/uni-popup.vue';
import datePicker from '../../../uni_modules/nj-birthday-picker/components/nj-birthday-picker/nj-birthday-picker.vue'
import UniSwipeAction from '../../../uni_modules/uni-swipe-action/components/uni-swipe-action/uni-swipe-action.vue'
import uniSwipeActionItem from '../../../uni_modules/uni-swipe-action/components/uni-swipe-action-item/uni-swipe-action-item.vue'
import { memoryDayAdd, memoryDayDel, memoryDayListByType, memoryDayUpdate } from '@/api/memoryDay/memoryDay';

interface Day {
    id?: number;
    title?: string;
    targetTime?: string;
    nextDays?: number; // 下次天数
    firstDays?: number; // 已过天数
    type?: number; // 0-公历, 1-农历
}

// Tab栏状态
const tabNumNow = ref(0); // 当前选中的Tab索引
const classNameArr = ref<string[]>(['tab-item-active', 'tab-item-default']); // Tab栏的类名数组
const changeTab = (tabNum: number) => {
    tabNumNow.value = tabNum;
    classNameArr.value = ['tab-item-default', 'tab-item-default'];
    classNameArr.value[tabNum] = 'tab-item-active';
    init();
};

// 纪念日列表
const days = ref<Day[]>(null);
const init = async () => {
    const res = await memoryDayListByType(tabNumNow.value);
    days.value = res.data;
}
onMounted(() => {
    init();
})

// 表单弹窗相关
const showPopup = ref(false);
const dayPopup = ref(null);
const openDayPopup = () => {
    if (dayPopup.value) {
        showPopup.value = true;
        dayPopup.value.open("dayPopup");
    }
};

// 日期类型选项
const dateTypeOptions = ['公历', '农历'];

// 纪念日表单数据
interface NewDay {
    title?: string;
    targetTime?: string;
    type?: number;
}
const newDay = ref<NewDay>({
    title: '',
    targetTime: '',
    type: 0, // 默认公历
});

// 选择日期类型
const onDateTypeChange = (event: any) => {
    newDay.value.type = event.detail.value;
};

// 关闭弹窗
const closeTaskPopup = () => {
    if (dayPopup.value) {
        showPopup.value = false;
        dayPopup.value.close();
        newDay.value = { title: '', targetTime: '', type: 0 };
        currentDayId.value = null;
    }
};

// 添加纪念日
const addDay = async () => {
    if (newDay.value.title.trim() === '') {
        uni.showToast({
            title: '纪念日标题不能为空',
            icon: 'none',
        });
        return;
    }
    if (newDay.value.targetTime.trim() === '') {
        uni.showToast({
            title: '请选择日期',
            icon: 'none',
        });
        return;
    }
    const [year, month, day] = newDay.value.targetTime.split('-');
        // 格式化为两位数
        const formattedMonth = month.padStart(2, '0');
        const formattedDay = day.padStart(2, '0');
        // 拼接为 yyyy/MM/dd 格式
        const formattedDate = `${year}-${formattedMonth}-${formattedDay}`;
    const day2: Day = {
        title: newDay.value.title,
        type: newDay.value.type,
        targetTime: formattedDate
    }
    if (currentDayId.value != null || currentDayId.value != undefined) {
        // 修改
        day2.id = currentDayId.value;
        await memoryDayUpdate(day2);
    } else {
        // 新增
        await memoryDayAdd(day2);
    }
    init();
    closeTaskPopup();
};

// 可移动按钮
const position = ref({ left: uni.getSystemInfoSync().screenWidth - 70, top: uni.getSystemInfoSync().screenHeight - 140 });
const startTouch = ref({ x: 0, y: 0 });
const isDragging = ref(false);
const onTouchStart = (event: TouchEvent) => {
    const touch = event.touches[0];
    startTouch.value = {
        x: touch.clientX - position.value.left,
        y: touch.clientY - position.value.top,
    };
    isDragging.value = true;
};

const onTouchMove = (event: TouchEvent) => {
    if (!isDragging.value) return;
    const touch = event.touches[0];
    const newLeft = touch.clientX - startTouch.value.x;
    const newTop = touch.clientY - startTouch.value.y;
    const systemInfo = uni.getSystemInfoSync();
    const maxLeft = systemInfo.screenWidth - 50;
    const maxTop = systemInfo.screenHeight - 100;
    position.value.left = Math.max(0, Math.min(newLeft, maxLeft));
    position.value.top = Math.max(0, Math.min(newTop, maxTop));
};

const onTouchEnd = () => {
    isDragging.value = false;
};


// 弹窗表单
const pickerRef = ref(null);
const openSelectDate = () => {
    pickerRef.value.show("pickerRef");
}
const handleSelectDate = (e) => {
    console.log("选择时间111", e);
    console.log("日期类型: ", newDay.value.type);
    if (newDay.value.type == 1) {
        // 农历
        newDay.value.targetTime = e.lunarDate;
        console.log("农历: ", newDay.value.targetTime);
    } else {
        // 公历
        newDay.value.targetTime = e.date;
        console.log("公历: ", newDay.value.targetTime);
    }
}
const defaultDate = ref(new Date());
const defaultLunar = ref(false);


// 列表元素左滑
// 处理编辑按钮点击事件
const currentDayId = ref(null);
const handleEdit = (day: Day) => {
    console.log('编辑任务:', day);
    newDay.value.type = day.type;
    newDay.value.targetTime = day.targetTime;
    newDay.value.title = day.title;
    currentDayId.value = day.id;
    openDayPopup()
};

// 处理删除按钮点击事件
const handleDelete = async (taskId: number) => {
    console.log('删除任务:', taskId);
    await memoryDayDel(taskId);
    init()
};
</script>

<style scoped>
.container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: flex-start;
    text-align: center;
    height: 98vh;
    padding: 1vh 20px;
    overflow-y: hidden;
    overflow-x: hidden;
    background-color: #fff;
}

.bottom-tab {
    display: flex;
    justify-content: space-around;
    background-color: rgba(255, 255, 255, 0);
    padding: 10px 0;
    height: 30px;
    width: 90vw;
    border-top: 1px solid #eee;
    text-align: center;
}

.tab-item-default {
    font-size: 14px;
    color: #4c88ad;
    height: 100%;
    width: 25%;
    opacity: 0.5;
}

.tab-item-active {
    font-size: 14px;
    height: 100%;
    width: 25%;
    color: #4c88ad;
}

.task-list {
    margin-top: 10px;
    padding: 10px;
    width: 96%;
    border: 1px solid #ddd;
    border-radius: 8px;
    overflow-y: scroll;
    overflow-x: hidden;
}

.task-item {
    position: relative;
    display: flex;
    align-items: center;
    padding: 10px;
    margin-bottom: 10px;
    height: 40px;
    border-bottom: 1px solid #eee;
    border-radius: 10px;
    border: 1px solid #ddd;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.task-time {
    position: absolute;
    left: 10px;
    bottom: 10px;
    font-size: 10px;
    color: rgba(82, 74, 74, 0.5);
}

.task-title {
    position: absolute;
    left: 10px;
    top: 10px;
    font-size: 14px;
    margin-top: 8px;
    flex-grow: 1;
}

.floating-button {
    position: fixed;
    bottom: 20px;
    right: 20px;
    width: 50px;
    height: 50px;
    background-color: #007AFF;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 24px;
    cursor: pointer;
}

.popup-content {
    background-color: #ffffff;
    padding: 20px;
    border-radius: 10px;
    width: 300px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.form {
    display: flex;
    flex-direction: column;
    gap: 15px;
}

.task-input {
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 5px;
    font-size: 14px;
}

.date-picker {
    display: flex;
    flex-direction: column;
    gap: 10px;
}

.picker {
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 5px;
    font-size: 14px;
}

.button-group {
    display: flex;
    justify-content: space-between;
    gap: 10px;
}

.add-button {
    background-color: #4CAF50;
    color: white;
    border: none;
    padding: 10px 20px;
    border-radius: 5px;
    font-size: 14px;
    cursor: pointer;
}

.cancel-button {
    background-color: #f44336;
    color: white;
    border: none;
    padding: 10px 20px;
    border-radius: 5px;
    font-size: 14px;
    cursor: pointer;
}

.add-button:hover,
.cancel-button:hover {
    opacity: 0.9;
}

.floating-button {
    position: fixed;
    right: 10px;
    bottom: 10px;
    width: 50px;
    height: 50px;
    background-color: #007aff;
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
    z-index: 9999;
}

.plus-icon {
    color: white;
    font-size: 24px;
    font-weight: bold;
}

/* 距离第一次的样式，固定在右下角，带有渐变文字效果 */
.task-count-first {
    position: absolute;
    /* 使用绝对定位 */
    bottom: 10px;
    /* 固定在父容器底部10px处 */
    right: 10px;
    /* 固定在父容器右侧10px处 */
    font-size: 16px;
    font-weight: 600;
    color: transparent;
    -webkit-background-clip: text;
    background-clip: text;
    background-image: linear-gradient(45deg, #ff7e5f, #feb47b);
    font-family: 'Arial', sans-serif;
    letter-spacing: 0.5px;
    text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.1);
    /* 为了适配不同屏幕，可以考虑使用媒体查询来调整bottom和right的值 */
}

/* 距离下一次的样式，同样固定在右下角，带有渐变文字效果 */
.task-count-next {
    position: absolute;
    /* 使用绝对定位 */
    bottom: 30px;
    /* 固定在父容器底部10px处 */
    right: 10px;
    /* 固定在父容器右侧10px处 */
    font-size: 16px;
    font-weight: 600;
    color: transparent;
    -webkit-background-clip: text;
    background-clip: text;
    background-image: linear-gradient(45deg, #8e44ad, #4a90e2);
    font-family: 'Arial', sans-serif;
    letter-spacing: 0.5px;
    text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.1);
    /* 同样，为了适配不同屏幕，可以考虑使用媒体查询 */
}

.form-item {
    display: flex;
    align-items: center;
    height: 60px;
    flex-direction: row;
    border-bottom: 1px solid #eee;
}

.form-title {
    width: 60px;
    font-size: 18px;
    font-weight: normal;
    color: #333;
}

.form-value {
    flex: 1;
    font-size: 18px;
    font-weight: normal;
    color: #333;
}

.swipe-buttons {
    display: flex;
    align-items: center;
    height: 100%;
}

.edit-btn,
.delete-btn {
    /* margin: 10px; */
    border-radius: 0;
    /* 完成按钮背景色 */
    color: white;
    border-radius: 10px;
}

.edit-btn {
    background-color: #FFC107;
    /* 编辑按钮背景色 */
}

.delete-btn {
    background-color: #F44336;
    /* 删除按钮背景色 */
}
</style>